package com.margo.project.redis.lock.service;

import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

@Component
public class RedisDistributedLock {
	
	private final Logger logger=LoggerFactory.getLogger(RedisDistributedLock.class);
	@Autowired
	private StringRedisTemplate stringRedisTemplate;
	
	/**
	 * 
	 * Absent adj 缺席; 不在; 不存在; 缺少; 心不在焉的; 出神的; 美[ˈæbsənt , æbˈsent]
	 * Present adj.	现存的; 当前的; 出现; 在场; 出席; 存在;   美[ˈpreznt , prɪˈzent]
	 * 加锁
	 * @param objectId
	 * @param millisecond
	 * @return
	 */
	public boolean lock(String objectId,long millisecond) {
		//Boolean success= stringRedisTemplate.opsForValue().setIfPresent(objectId, "lock", millisecond, TimeUnit.MILLISECONDS);
		Boolean success= stringRedisTemplate.opsForValue().setIfAbsent(objectId, "lock", millisecond, TimeUnit.MILLISECONDS);
		logger.info("redis锁:"+success);
		return success != null && success;
	}
	
	/**
	 * 释放锁
	 * @param objectId
	 */
	public void releaseLock(String objectId) {
		stringRedisTemplate.delete(objectId);
	}

}
